/*
 * @Description:
 * @Author: fhw
 * @Date: 2022-12-31 16:53:42
 */
import { defineComponent, onMounted, PropType, reactive, ref, onUnmounted, nextTick, Slot, watch } from 'vue'
import './style.scss'
export interface Axis {
	x: number
	y: number
}
const props = {
	visible: Boolean as PropType<boolean>,
	loading: {
		type: Boolean as PropType<boolean>,
		default: false,
	},
	axis: {
		type: Object as PropType<Axis>,
	},
} as const
export default defineComponent({
	props,
	emits: ['update:visible', 'cancel'],
	setup(props, { emit, slots }) {
		const followRef = ref()
		const pageState = reactive({
			x: 0,
			y: 0,
			width: 0,
			height: 0,
			visible: false,
		})
		onMounted(() => {
			// 全局点击事件
			document.addEventListener('mouseup', onMouseup, false)
		})
		onUnmounted(() => {
			document.removeEventListener('mouseup', onMouseup, false)
		})
		function onMouseup(e: any) {
			if (followRef.value) {
				// 判断鼠标点击的区域是否在tree里面，否则关闭弹窗
				if (!followRef.value.contains(e.target) && !props.loading) {
					emit('update:visible', false)
					emit('cancel')
				} else {
					return
				}
			}
			getXY(e)
		}
		watch(
			() => props.visible,
			(visible) => {
				if (!visible) return
				nextTick(() => {
					getXY(followRef.value.getBoundingClientRect())
				})
			}
		)
		function getXY(e: { target?: any; x: number; y: number; height: number; width: number }) {
			const { x, y, width } = e
			const { innerWidth } = window
			if (x + width >= innerWidth) {
				pageState.x = props.axis?.x ?? x - width
			} else {
				pageState.x = props.axis?.x ?? x
			}
			pageState.y = props.axis?.y ?? y
		}
		return () =>
			props.visible && (
				<div
					style={{ left: `${pageState.x}px`, top: `${pageState.y}px`, position: 'absolute' }}
					id="follow"
					ref={followRef}
				>
					{slots && (slots.default as Slot)()}
				</div>
			)
	},
})
